<template>
    <div class="table">
        <div class="container">
            <el-row justify="end">
                <div class="handle-box">
                    <el-input v-model="select_word" placeholder="输入手机号码" class="handle-input mr10"></el-input>
                    <el-button type="primary" icon="search" @click="search();cur_page = 1">搜索</el-button>
                </div>
                <!-- <el-col :span="24" v-if="authority">
                    <el-button style="float: right;margin: 10px 0" type="primary" plain size="medium" @click="newInvite()">新增邀请码</el-button>
                </el-col> -->
            </el-row>
            <el-table :data="tableData" border ref="multipleTable"  v-loading="loadingFlag">
                <el-table-column prop="invite_code" label="验证码"></el-table-column>
                <el-table-column prop="date" label="日期">
                    <template slot-scope="scope">
                        {{ scope.row.create_time | formatTime}}
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="电话号码">
                </el-table-column>
                <el-table-column prop="price" label="优惠金额">
                    <template slot-scope="scope">
                        {{((scope.row.price -0 )/100).toFixed(2)}} 元
                    </template>
                </el-table-column>
                <el-table-column prop="state" label="使用情况">
                    <template slot-scope="scope">
                        {{ scope.row | orderState}}
                    </template>
                </el-table-column>
                <el-table-column prop="nickName" label="使用人微信号">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button v-if="!scope.row.nickName" type="danger" @click="delInvitationCodeShow(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination @current-change="handleCurrentChange" :current-page.sync="cur_page" layout="prev, pager, next, jumper" :total="total" :page-size="10">
                </el-pagination>
            </div>
        </div>
        <!-- 删除批次管理 提示框 -->
        <el-dialog title="提示" :visible.sync="visible" center>
            <div class="del-dialog-cnt">
                <el-table :data="newTable" border ref="multipleTable" v-if="!batchAddFlag">
                    <el-table-column label="手机号码">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.phone" placeholder="请输入手机号码"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="优惠金额">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.price" placeholder="请输入优惠金额"></el-input>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column  label="邀请码" prop="code">
                    </el-table-column> -->
                    <!-- <el-table-column  label="操作" prop="code">
                        <template slot-scope="scope">
                            <el-button type="primary" @click="createCode(scope.row,scope.$index)">生成邀请码</el-button>
                        </template>
                    </el-table-column> -->
                </el-table>
                <div class="batch-add" v-if="batchAddFlag">
                    <el-row>
                        <el-col :span="6">
                            <div class="grid-content bg-purple">优惠金额</div>
                        </el-col>
                        <el-col :span="18">
                            <div class="grid-content bg-purple-light">
                                <el-input v-model="batchPrice" placeholder="请输入优惠金额"></el-input>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row style="margin-top: 20px;">
                        <el-col :span="6">
                            <div class="grid-content bg-purple">手机号码（不可存在空格，只允许存在换行。重点注意）</div>
                        </el-col>
                        <el-col :span="18">
                            <div class="grid-content bg-purple-light">
                                <el-input type="textarea" :autosize="{minRows:4}" v-model="batchPhone" placeholder="请输入手机号码"></el-input>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <div style="text-align: left">
                    <el-button type="success" icon="el-icon-plus" @click="addCode()">新增</el-button>
                    <el-button type="primary" icon="el-icon-plus" @click="batchAddFlagShow()">批量添加</el-button>
                </div>
                <div style="text-align: right">
                    <el-button @click="visible = false">取 消</el-button>
                    <el-button type="primary" @click="submitSend()">发送邀请码</el-button>
                </div>
            </span>
        </el-dialog>
        <el-dialog title="提示" :visible.sync="delVisible" center>
            <div class="del-dialog-cnt">
                <p>是否确定删除该邀请码？</p>
            </div>
            <span slot="footer" class="dialog-footer">
                <div style="text-align: right">
                    <el-button @click="delVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirmDelCode()">确定</el-button>
                </div>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    obtainInvitationCode,
    saveInvitationCode,
    obtainInvitationCodeList,
    sendInvitationCode,
    searchInvitationCode,
    delInvitationCode
} from "@/config/api";
import axios from "axios"; //引入axios
import { zhouUrl } from "@/config/env";
import { dateRegExp } from "@/config/filter";
export default {
    name: "basetable",
    data() {
        return {
            loadingFlag: false,
            select_word: "",
            tableData: [],
            cur_page: 1,
            // 总条数
            total: 0,
            visible: false,
            is_search: false,
            // 新增邀请码的表单
            newTable: [
                {
                    phone: "",
                    price: "",
                    code: ""
                }
            ],
            // 权限
            authority: true,
            // 邀请码删除弹窗提示
            delVisible: false,
            // 删除的条目
            checkDate: {},
            // 批量添加 显示
            batchAddFlag: false,
            // 批量添加的时候，输入的金额
            batchPrice: '',
            // 批量添加的时候，输入的手机号码
            batchPhone:'',
            // 过渡
            fullscreenLoading: false,
            // 过渡对象
            loadingEvt: null,
            // 错误的手机号码
            errPhone: []
        };
    },
    filters: {
        formatTime(time) {
            return dateRegExp(time - 0, "yyyy-MM-dd hh:mm:ss");
        },
        formatState(state) {
            let str = "";
            // 0 未使用 1已使用 2已过期
            if (state == 0) {
                str = "未使用";
            }
            if (state == 1) {
                str = "已使用";
            }
            if (state == 2) {
                str = "已过期";
            }
            return str;
        },
        orderState (item) {
            let str = '';
            // if (item.status == 1) {
            //     str = '未付款'
            // } else if (item.status == 2 && item.state == 1) {
            //     str = '已使用'
            // } else if (item.status == 3 && item.state == 1) {
            //     str = '有使用，订单未成功'
            // } else {
            //     str = '未使用'
            // }
            if (item.state === 1) {
                str = '已使用'
            } else if (item.state === 2) {
                str = '已过期'
            } else {
                str = '未使用'
            }

            
            return str;
        }
    },
    computed: {},
    created() {},
    mounted() {
        console.log(localStorage.getItem('ms_username'), '......ms_username')
        if (localStorage.getItem('ms_username') === 'admin') {
            // 权限
            this.authority = true
            this.getData();
        }
        if (localStorage.getItem('ms_username') === 'service') {
            // 权限
            this.authority = false
        }
        
    },
    methods: {
        // 开启过渡
        openFullScreen () {
            this.loadingEvt = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        },
        // 关闭过渡
        closeFullScreen () {
            this.loadingEvt.close();
        },
        // 获取数据
        async getData() {
            this.loadingFlag = true;
            let data = await obtainInvitationCodeList(this.cur_page);
            console.log("数据", data);
            this.tableData = data.list;
            this.total = data.total;
            this.loadingFlag = false;
        },
        // 分页导航
        handleCurrentChange(val) {
            this.cur_page = val;
           
            if (this.is_search) {
                this.search();
            } else {
                this.getData();
            }
            
        },
        // 新增邀请码 显示
        async newInvite() {
            this.visible = true;
            this.newTable = [
                {
                    phone: "",
                    price: ""
                }
            ];
        },
        // 删除邀请码弹窗显示
        async delInvitationCodeShow (row) {
            this.delVisible = true;
            this.checkDate = row
        },
        // 确定删除邀请码
        async confirmDelCode () {
            console.log('删除邀请码',this.checkDate)
             
            await delInvitationCode(this.checkDate.phone,this.checkDate.invite_code)
                .then( res => {
                    if (res.status === 200) {
                        this.$notify.success({
                            title: "成功",
                            message: "删除成功"
                        });
                    } else {
                       this.$notify.error({
                            title: "错误",
                            message: res.msg
                        }); 
                    }
                    this.delVisible = false;
                    if (this.is_search) {
                        this.search();
                    } else {
                        this.getData();
                    }
                })
                .catch( err => {
                    this.$notify.error({
                        title: "错误",
                        message: "网络拥堵，稍后再试"
                    });
                })
        },
        // 生成验证码
        async createCode(row, index) {
            console.log("生成验证码", row, index);
        },
        // 表单 新增
        addCode() {
            if (this.batchAddFlag) {
                this.newTable = [{ 
                    phone: "",
                    price: ""
                }];
                this.batchAddFlag = false;
                this.errPhone = [];
            } else {
                this.newTable.push({
                    phone: "",
                    price: ""
                });
            }
        },
        // 批量添加
        batchAddFlagShow () {
            this.errPhone = [];
            this.batchAddFlag = true;
            this.batchPhone = '';
            this.batchPrice = '';
        },
        // 发送验证
        async submitSend() {
           
            this.openFullScreen();  // 开启过渡
            // 错误手机号码存储
            this.errPhone = [];
            if (this.batchAddFlag) {
                if (!this.batchPrice) {
                    this.$notify.error({
                        title: "错误",
                        message: "请输入优惠金额"
                    });
                    this.closeFullScreen();
                    return false;
                } 
                this.newTable = [];
                let phones = this.batchPhone.split('\n')
                for (let i = 0; i < phones.length; i++) {
                    if (phones[i]) {
                        phones[i] = phones[i].replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, "");  // 去取空格
                        console.log(phones[i].length)
                        if (phones[i].length != 11){
                            // this.$notify.error({
                            //     title: "错误",
                            //     message: "请输入正确的手机号码"
                            // });
                            // this.closeFullScreen();
                            // break
                            this.errPhone.push({
                                phone:phones[i],
                                price:this.batchPrice
                            })
                        } else if (phones[i].length == 11) {
                            this.newTable.push({
                                phone:phones[i],
                                price:this.batchPrice
                            })
                        }
                        
                    }
                }
            } else {
                 // 非批量增加
                 for (let i = this.newTable.length - 1; i >= 0 ;i--) {
                    this.newTable[i].phone = this.newTable[i].phone.replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, "");  // 去取空格
                    if (this.newTable[i].phone.length != 11) {
                        this.errPhone.push({
                            phone: this.newTable[i].phone,
                            price: this.newTable[i].price
                        });
                        this.newTable.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                    }
                 }
            }

            for (let i = this.newTable.length - 1; i >= 0 ;i--) {
                if (this.newTable[i].phone && this.newTable[i].price) {
                    // 获取邀请码
                    await obtainInvitationCode()
                        .then(async res => {
                            return new Promise( async (resolve,reject) => {
                                console.log(res.data);
                                // 把这个邀请码保存到数据库。数据库保存好之后才给他发送短信
                                let save_res = await saveInvitationCode(
                                    res.data,
                                    this.newTable[i].phone,
                                    (this.newTable[i].price - 0) *100
                                );
                                console.log("数据库保存验证码", save_res.status);
                                // 数据通过发送验证码
                                if (save_res.status == 200) {
                                    console.log('发送验证码',this.newTable[i].phone)
                                    if (this.newTable[i].phone.length == 11) {
                                        console.log(this.newTable[i].phone,'正确手机号码')
                                        // 发送验证给用户
                                        await sendInvitationCode(res.data,this.newTable[i].phone)
                                            .then(res => {
                                                console.log('验证码',res)
                                                if (res.status === 200) {
                                                    this.newTable.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                                                }
                                                resolve()
                                            })
                                            .catch(err => {
                                                this.$notify.error({
                                                    title: "错误",
                                                    message: "发送失败"
                                                });
                                            });
                                    } else {
                                        // this.$notify.error({
                                        //     title: "错误",
                                        //     message: "手机号码输入错误"
                                        // });
                                        this.errPhone.push({
                                            phone:this.newTable[i].phone,
                                            price: this.newTable[i].price
                                        })
                                    }
                                } else {
                                    this.$notify.error({
                                        title: "错误",
                                        message: res.msg
                                    });
                                }
                            })
                            
                        })
                        .catch(err => {
                            console.error(err);
                        });
                }
            }
            // 发送失败提示
            if (this.errPhone.length) {
                this.newTable = this.errPhone;
                this.$notify.error({
                    title: "错误",
                    message: this.errPhone.length + "条发送失败"
                });
                // 批量添加，发送失败的手机号码
                if (this.batchAddFlag) {
                    let arr = [];
                    for (let i =0; i < this.errPhone.length;i++) {
                        arr.push(this.errPhone[i]['phone'])
                    }
                    this.batchPhone = arr.join('\n');
                }
                this.closeFullScreen(); // 开闭过渡
            } else {
                // 全部发送完成，退出弹窗
                this.visible = false;
                this.batchPhone = '';
                this.batchPrice = '';
                this.closeFullScreen(); // 开闭过渡
            }
            // 发送完重新获取数据
            await this.getData();
        },
        // 学员搜索
        async search() {
            if (!this.select_word) {
                this.cur_page = 1
                this.getData();
                this.is_search = false;
                return false;
            }
            this.is_search = true;
            this.loadingFlag = true;
            await searchInvitationCode(this.select_word.replace(/(^\s*)|(\s*$)/g,""), this.cur_page)
                .then( res => { 
                    console.log('学员搜索',res)
                    if (res.status === 200) {
                        
                        this.tableData = res.list
                        this.total = res.total
                    } else {
                        this.$message.error("搜索失败");
                    }
                    this.loadingFlag = false;
                })
        },
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.del-dialog-cnt {
    font-size: 16px;
    text-align: center;
}
.batch-add {
    text-align: left;
}
</style>
